<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'
import type { FormRules } from 'element-plus'
import { roleList } from '@/plugins/stratocirri-plus/modules/permission/api/roles'

interface Props {
  data?: Record<string, any> | never | null
  status: string
}

const props = withDefaults(defineProps<Props>(), {
  data: null,
  status: 'add'
})

const formRef = ref()

const form = reactive<Record<string, any>>({})

const rules = reactive<FormRules>({
  seedballBatchName: [{ required: true, message: '种球批次名称不能为空!', trigger: 'change' }]
})

const initForm = () => {
  if (props.data) {
    Object.keys(props.data).forEach((key: string) => {
      form[key] = props.data![key]
    })
  }
}

const formatForm = () => {
  const result: Record<string, any> = {}
  Object.keys(form).forEach((key: string) => {
    result[key] = form[key]
  })
  return result
}

const submitForm = () => {
  return new Promise<any>((resolve) => {
    formRef.value.validate((valid: boolean) => {
      let res = null
      if (valid) {
        res = formatForm()
      }
      resolve(res)
    })
  })
}

defineExpose({
  submitForm
})

const rolesOpts = ref<any[]>([])

const getOptions = async () => {
  let res: any = await roleList()
  rolesOpts.value = res.map((item: any) => {
    return {
      label: item.roleName,
      value: item.roleId
    }
  })
}
getOptions()

onMounted(() => {
  initForm()
})
</script>

<template>
  <div class="form-wrapper">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="100px" class="seedball-due-detail-form">
      <el-form-item label="名称：" prop="enterpriseTypeName">
        <el-input v-model="form.enterpriseTypeName" type="text" placeholder="请输入内容"> </el-input>
      </el-form-item>

      <el-form-item v-if="status == 'add'" label="角色：" prop="roleId">
        <el-select v-model="form.roleId" placeholder="角色">
          <el-option v-for="item in rolesOpts" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
    </el-form>
  </div>
</template>

<style lang="scss" scoped>
.seedball-due-detail-form {
  width: 500px;
  @include flex(row, flex-start, center);
  flex-wrap: wrap;
  .el-form-item {
    // width: 50%;
    padding-right: 50px;
    box-sizing: border-box;
  }
}
</style>
